package com.jackrain.nea.fc.vp.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ChrusersWebQueryCmd;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.vp.api.ViewCvouAddCmd;
import com.jackrain.nea.fc.vp.mapper.ViewCvouMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import com.jackrain.nea.web.face.User;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;

/**
 * 会员中心购物券服务接口service层
 *
 * @author wuwenxue
 * @date 2017/11/13
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "vp")
public class ViewCvouAddCmdImpl extends CommandAdapter implements ViewCvouAddCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Reference(version = "1.0", group = "cp")
    private ChrusersWebQueryCmd chrusersWebQueryCmd;

    @Override
    @Transactional
    public ValueHolder execute(HashMap map) throws NDSException {
        ViewCvouMapper viewCvouMapper = ApplicationContextHandle.getBean(ViewCvouMapper.class);
        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewCvouAddCmdImpl--param-->{}",param);

        if (null == param || (!param.containsKey("data")) || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }

        User user = chrusersWebQueryCmd.getUser("INTER99999");

        JSONArray jsonArray = param.getJSONArray("data");

        if (jsonArray.size() > 100) {
            throw new NDSException("微信端数据过大，无法处理！");
        }

        StringBuffer sb = new StringBuffer("insert into VP_C_VOU (ECODE,VOUTYPE,REMARK,ISVERIFYED,OWNERID," +
                "CREATIONDATE,MODIFIERID,MODIFIEDDATE,AD_CLIENT_ID,AD_ORG_ID,ID,MODIFIERNAME,MODIFIERENAME," +
                "OWNERNAME,OWNERENAME) values ");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());

            /*HashMap hashMap = new HashMap(16);
            hashMap.put("tableName", "USERS");
            hashMap.put("fields", "ID,ENAME");
            hashMap.put("type", HashMap.class);
            JSONObject whereJson = new JSONObject();
            whereJson.put("NAME", "INTER99999");
            hashMap.put("whereKeys", whereJson);
            //Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.web.QueryCmd", "cp", "2");
            HashMap cpJS = (HashMap) queryCmd.queryTable(hashMap);*/

            /*//固定传输用户编号：INTER99999
            if (null == cpJS || (!cpJS.containsKey("ID")) || (!cpJS.containsKey("ENAME"))) {
                throw new NDSException("INTER99999用户错误！");
            }
            Long user = (Long) cpJS.get("ID");*/
            //ename
            String ename = user.getEname();
            //name
            String name = user.getName();

            String newRemark = null;
            String remark = jsonObject.getString("REMARK");
            if (remark == null) {
                newRemark = null;
            } else {
                newRemark = "'" + remark + "'";
            }

            String newEname = null;
            if (null == ename) {
                newEname = null;
            } else {
                newEname = "'" + ename + "'";
            }

            String newName = null;
            if (null == name) {
                newName = null;
            } else {
                newName = "'" + name + "'";
            }

            if (null == jsonObject.getString("ECODE")) {
                throw new NDSException("券号不能为空！");
            }

            //用户人修改人ID
            Long userID = Integer.valueOf(user.getId()).longValue();
            //所属公司
            Long clientID = Integer.valueOf(user.getClientId()).longValue();
            //所属组织
            Long orgID = Integer.valueOf(user.getOrgId()).longValue();


            sb.append("(");
            //券号-->FC
            sb.append("'" + jsonObject.getString("ECODE") + "'");
            //券类型-->FC
            sb.append("," + "'VOU1'");
            //备注-->FC
            sb.append("," + newRemark);
            //是否核销-->FC
            sb.append("," + "'N'");
            //创建人-->FC
            sb.append("," + userID);
            //创建时间-->FC
            sb.append(",'" + timestamp + "'");
            //修改人-->FC
            sb.append("," + userID);
            //修改时间-->FC
            sb.append(",'" + timestamp + "'");
            //所属公司
            sb.append("," + clientID);
            //所属组织
            sb.append("," + orgID);
            //ID
            sb.append("," + Tools.getSequence("VP_C_VOU"));
            sb.append("," + newName);
            sb.append("," + newEname);
            sb.append("," + newName);
            sb.append("," + newEname);
            sb.append(")");
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
//        log.info("微信端新增购物券sql----->" + sb.toString());
        int insert = viewCvouMapper.insertAll(sb.toString());
        if (insert < 0) {
            throw new NDSException("新增失败");
        } else {
            vh.put("status", 0);
            vh.put("message", Resources.getMessage("新增成功"));
        }

        return vh;
    }
}
